package net.whippetcode.plugins.intellij.hudson.ui.job;

import net.whippetcode.hudson.domain.HudsonView;
import net.whippetcode.hudson.manager.JobManager;
import net.whippetcode.hudson.util.JavaUtil;
import net.whippetcode.plugins.intellij.hudson.domain.job.Job;
import net.whippetcode.plugins.intellij.hudson.domain.job.Status;
import net.whippetcode.plugins.intellij.hudson.domain.job.Workspace;
import net.whippetcode.plugins.intellij.hudson.parser.ws.PopulateWorkspaceTask;
import net.whippetcode.plugins.intellij.hudson.util.LogUtil;
import net.whippetcode.util.task.ITask;

import java.net.URL;
import java.util.List;
import java.util.logging.Level;

/**
 * This class will contact the server and load the Jobs.
 * 
 * @author David A. Freels Sr.
 */
public class PopulateJobsTask implements ITask<PopulateJobsTaskResult>
{
	private static final long serialVersionUID = -8438156983860133692L;
	
	private String serverAddress;
	private URL serverURL;
	private PopulateJobsTaskResult result;

	public PopulateJobsTask(URL serverURL, String serverAddress)
	{
		this.serverURL = serverURL;
		this.serverAddress = serverAddress;
	}

	public void execute()
	{
		List<Job> jobs;
		try
		{
			jobs = JobBuilder.convertToPluginJob(JavaUtil.convertSeqToJList(JobManager.getJobsForView(new HudsonView("view", serverURL.toURI().toString()))), this.serverAddress);
		}
		catch (Exception e)
		{
			LogUtil.log(Level.SEVERE, e.getMessage(), e);
			return;
		}

		//Populate the first level of workspace.
		StringBuilder statusMessage = new StringBuilder("<html><body><table border=0>");
		Status status = Status.DISABLED;
		PopulateWorkspaceTask task;
		for (Job job : jobs)
		{
			statusMessage.append("<tr><td>").append(job.getName()).append("</td><td bgcolor=").append(job.getStatus() == Status.DISABLED ? "gray" : job.getStatus().name().toLowerCase()).append("></td></tr>");
			if (status.compareTo(job.getStatus()) > 0)
			{
				status = job.getStatus();
			}
			Workspace ws = (Workspace) job.getChildren().get(0);
			task = new PopulateWorkspaceTask(this.serverAddress, job.getName() + "/ws", ws);
			task.execute();
		}
		statusMessage.append("</table></body></html>");
		result = new PopulateJobsTaskResult(jobs, statusMessage.toString(), status);
	}

	public PopulateJobsTaskResult getResult()
	{
		return result;
	}
}
